package eu.webhib.webblog.gui.controller;

import eu.webhib.frmwrk.jsf.base.EditBaseController;
import eu.webhib.frmwrk.jsf.utils.JsfUtil;
import eu.webhib.frmwrk.jsf.utils.MsgUtil;
import eu.webhib.webblog.application.ApplMail;
import eu.webhib.webblog.domain.User;
import eu.webhib.webblog.gui.application.GuiApplication;
import eu.webhib.webblog.service.factory.ServiceFactory;
import eu.webhib.webblog.service.intf.UserService;
import javax.faces.bean.*;
import javax.faces.event.*;
import org.apache.log4j.Logger;

/**
 * Controller of the User Email Confirmation page
 */
@ManagedBean(name = "emailconf")
@SessionScoped
public class EmailConfirm extends EditBaseController {

   private static final Logger log = Logger.getLogger(EmailConfirm.class);
   private static UserService userService = ServiceFactory.getUserService();
   //
   private String additionalText;
   private boolean emailConfirmed = false;
   private User user;

   private enum ConfirmResult {

      OK, NOT_LOGGED_IN_USER, OTHER_FAILURE
   };

   // used by view do display additional text on page
   public String getAdditionText() {
      return additionalText;
   }

   public boolean isEmailConfirmed() {
      return emailConfirmed;
   }

   //
   // Email confirmation -----------------------------------
   //
   public void emailConfirmListener(ComponentSystemEvent event) {
      log.info("emailConfirmListener");
      new EditListenerClosure() {

         @Override
         protected void run(ComponentSystemEvent event) {
            doEmailConfirmListener();
         }
      }.start(event);
   }

   private void doEmailConfirmListener() {
      ConfirmResult res = checkEmailConfirmUser();
      switch (res) {
         case OK:
            setInfoMessage("info_emailconfirm_ok", user.getEmail());
            break;
         case NOT_LOGGED_IN_USER:
            setErrorMessage("error_emailconfirm_user");
            additionalText = MsgUtil.getMessageText("text_emailconfirmed_user");
            break;
         default:
            setErrorMessage("error_emailconfirm");
            additionalText = MsgUtil.getMessageText("text_emailconfirmed_failure");
      }
   }

   private ConfirmResult checkEmailConfirmUser() {
      emailConfirmed = false;
      String confirmSecret = JsfUtil.getRequestParam(ApplMail.emailConfirmUrlParam);
      log.debug("confirmSecret: " + confirmSecret);
      if (confirmSecret == null) {
         return ConfirmResult.OTHER_FAILURE;
      }
      // lookup user by confirmation secret
      user = userService.findByAttributeSingle("confirmSecret", confirmSecret);
      if (user == null) {
         log.warn("no user found for confirmSecret");
         return ConfirmResult.OTHER_FAILURE;
      }
      // check if email confirmation is pending for this user
      if (!user.checkEmailConfirm()) {
         log.warn("user not in right status");
         return ConfirmResult.OTHER_FAILURE;
      }
      Authentication auth = GuiApplication.getAuthenticationData();
      if (auth.isAuthenticated()) {
         if (!auth.getAuthenticatedUserId().equals(user.getId())) {
            return ConfirmResult.NOT_LOGGED_IN_USER;
         }
      }
      // set email confirmed for this user
      user.setEmailConfirmed();
      userService.save(user);
      emailConfirmed = true;
      return ConfirmResult.OK;
   }

   // Email confirmation successful or unsuccessful
   public String continueAction() {
      JsfUtil.sendRedirect(GuiApplication.getHistroyPageURI());
      return null;
   }
}
